import { ConfigEnv, UserConfigExport, loadEnv } from 'vite'
import { resolve } from 'path'
import { createVitePlugins } from './build/vite/plugin'
import { wrapperEnv } from './build/utils'

function pathResolve(dir: string) {
  return resolve(process.cwd(), '.', dir)
}

export default ({ command, mode }: ConfigEnv): UserConfigExport => {
  const root = process.cwd()
  const env = loadEnv(mode, root)
  const viteEnv = wrapperEnv(env)
  const isBuild = command === 'build'

  return {
    plugins: createVitePlugins(viteEnv, isBuild),
    ssr: {
      target: 'webworker',
    },
    resolve: {
      alias: [
        {
          find: 'vue-i18n',
          replacement: 'vue-i18n/dist/vue-i18n.cjs.js',
        },
        // /@/xxxx => src/xxxx
        {
          find: /\/@\//,
          replacement: pathResolve('src') + '/',
        },
        // /#/xxxx => types/xxxx
        {
          find: /\/#\//,
          replacement: pathResolve('types') + '/',
        },
        {
          find: /@\//,
          replacement: pathResolve('src') + '/',
        },
        // /#/xxxx => types/xxxx
        {
          find: /#\//,
          replacement: pathResolve('types') + '/',
        },
        {
          find: /~\//,
          replacement: pathResolve('package') + '/',
        },
        {
          find: /@build\//,
          replacement: pathResolve('build') + '/',
        },
      ],
    },
    esbuild: {
      //清除全局的console.log和debug
      drop: isBuild ? ['console', 'debugger'] : [],
    },
    server: {
      // 开启代理
      // proxy: {
      //   // 环境：'/dev-api'
      //   [env.VITE_APP_BASE_API]: {
      //     // 代理目标'http://localhost:3000'
      //     target: env.VITE_APP_SERVICE_URL,
      //     changeOrigin: true, //允许跨域
      //     // 重写url
      //     rewrite: (path) => path.replace(/^\/dev-api/, ''),
      //   },
      // },
    },
    preview: {
      host: true,
      port: 5173,
      open: true,
    },
  }
}
